var ttTypeWatch = (function(){ /* function to execute a callback, after the user has stopped typing for a specified amount of time */
	var timer = 0;
	return function(callback, ms){
		clearTimeout (timer);
		timer = setTimeout(callback, ms);
	}
})();

function cookieRead(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}

var transforms = {
	'object':{'tag':'div','class':'package ${show} ${type}','children':[
		{'tag':'div','class':'header','children':[
			{'tag':'div','class':function(obj){
				if( getValue(obj.value) !== undefined ) return('arrow hide');
				else return('arrow');
			}},
			{'tag':'span','class':'name','html':'${name}'},
			{'tag':'span','class':'value','html':function(obj) {
				var value = getValue(obj.value);
				if( value !== undefined ) return(" : " + value);
				else return('');
			}},
			{'tag':'span','class':'type','html':'${type}'}
		]},
		{'tag':'div','class':'children','children':function(obj){return(children(obj.value));}}
	]}
};

function visualize(json) {

	$('#ttPF_ConvertTAOutput').html('');

	$('#ttPF_ConvertTAOutput').json2html(convert('json',json,'open'),transforms.object);

	$('#ttPF_ConvertTAOutput, #ttPF_JSON_Filter').show();
	$('#ttPF_ConvertTA').hide();

	regEvents();

	$('#ttPF_ConvertTAOutput>div>div>div.package:last').removeClass('closed');
	$('#ttPF_ConvertTAOutput>div.package').css({marginLeft: '0'});
}

function getValue(obj) {
	var type = $.type(obj);

	//Determine if this object has children
	switch(type) {
		case 'array':
		case 'object':
			return(undefined);
			break;

		case 'function':
			//none
			return('function');
			break;

		case 'string':
			return("'" + obj + "'");
			break;

		default:
			return(obj);
			break;
	}
}

//Transform the children
function children(obj){
	var type = $.type(obj);

	//Determine if this object has children
	switch(type) {
		case 'array':
		case 'object':
			return(json2html.transform(obj,transforms.object));
			break;

		default:
			//This must be a litteral
			break;
	}
}

function convert(name,obj,show) {

	var type = $.type(obj);

	if(show === undefined) show = 'closed';

	var children = [];

	//Determine the type of this object
	switch(type) {
		case 'array':
			//Transform array
			//Itterrate through the array and add it to the elements array
			var len=obj.length;
			for(var j=0;j<len;++j){
				//Concat the return elements from this objects tranformation
				children[j] = convert(j,obj[j]);
			}
			break;

		case 'object':
			//Transform Object
			var j = 0;
			for(var prop in obj) {
				children[j] = convert(prop,obj[prop]);
				j++;
			}
			break;

		default:
			//This must be a litteral (or function)
			children = obj;
			break;
	}

	return( {'name':name,'value':children,'type':type,'show':show} );

}

function regEvents() {

	$('.header').click(function(){
		var parent = $(this).parent();

		if(parent.hasClass('closed')) {
			parent.removeClass('closed');
			parent.addClass('open');
		} else {
			parent.removeClass('open');
			parent.addClass('closed');
		}
	});
}


function ttProfileFetch(){

	$.getScript('https://ttdev204.googlecode.com/svn/common/jquery.json2html.js');
	$.getScript('https://ttdev204.googlecode.com/svn/common/json2html.js');

	$('html').empty();

	if (location.host=="barclaysbankplc.tt.omtrdc.net"){
		$('html').html('<form style="padding: 30px;border: 1px solid rgb(20, 111, 158);width: 90%;margin: 20px; position: relative;" id="ttPF_form">' +
			'<label for="ttPF_MembID">Please provide Membership ID for Profile to be fetched</label>' +
			'<input type="text" id="ttPF_MembID" name="ttPF_MembID" style="display:block; margin-top: 10px; width: 350px;" />' +
			'<input type="submit" value="Profile Fetch" id="ttPF_CTA" style="display: inline-block; margin-top: 10px; float: left;" /> ' +
			'<div id="ttFetchLoaderIco" style="display: none;width: 20px;height: 20px;float: left;margin-left: 10px;margin-top: 8px;"><img src="https://ttdev204.googlecode.com/svn/common/img/bs_ajax_loader.gif" style="width: 100%; height: 100%;"></div>' +
			'<p id="ttPF_RAWText" style="display: none; margin-top: 20px; clear: both; float: left;">RAW Profile</p>' +
			'<div id="ttPF_RAW" style="display: none; width: 100%; height: 150px; border: 1px solid rgb(20, 111, 158); margin-top: 0; overflow: auto;"></div>' +
			'<p id="ttPF_ConvertTAText" style="display: none; margin-top: 20px;clear: both; float: left;">Visualized JSON:</p>' +
			'<textarea name="ttPF_ConvertTA" id="ttPF_ConvertTA" style="display: none; width: 100%; height: 300px;clear: both; float: left;"></textarea>' +
			'<div id="ttPF_ConvertTAOutput" style="display: none; margin-top: 10px; width: 100%; max-height: 300px; overflow: auto;"></div>' +
			'<input type="text" placeholder="type here for filter, remove all for no filter" value="" id="ttPF_JSON_Filter" style="display: none; margin-top: 10px;margin-top: 10px;float: right;width: 50%;text-align: right;padding: 2px 10px;" /> ' +
			'<div style="clear:both;"></div>' +
			'</form>');

	}else{

		$('html').html('<form style="padding: 30px;border: 1px solid rgb(20, 111, 158);width: 90%;margin: 20px; position: relative;" id="ttPF_form">' +
			'<label for="ttPF_MembID">Please provide Membership ID for Profile to be fetched</label>' +
			'<input type="text" id="ttPF_MembID" name="ttPF_MembID" style="display:block; margin-top: 10px; width: 350px;" />' +
			'<input type="submit" value="Profile Fetch" id="ttPF_CTA" style="display: inline-block; margin-top: 10px; float: left;" /> ' +
			'<div id="ttFetchLoaderIco" style="display: none;width: 20px;height: 20px;float: left;margin-left: 10px;margin-top: 8px;"><img src="https://ttdev204.googlecode.com/svn/common/img/bs_ajax_loader.gif" style="width: 100%; height: 100%;"></div>' +
			'<p id="ttPF_RAWText" style="display: none; margin-top: 20px;clear: both; float: left;">RAW Profile (select all, and copy from here)</p>' +
			'<iframe id="ttPF_Iframe" src="about:blank" style="display: none; width: 100%; height: 150px; border: 1px solid rgb(20, 111, 158); margin-top: 0;"></iframe>' +
			'<p id="ttPF_ConvertTAText" style="display: none; margin-top: 20px;">Paste here and press [JSON Visualize]</p>' +
			'<textarea name="ttPF_ConvertTA" id="ttPF_ConvertTA" style="display: none; width: 100%; height: 300px;"></textarea>' +
			'<div id="ttPF_ConvertTAOutput" style="display: none; margin-top: 10px; width: 100%; max-height: 300px; overflow: auto;"></div>' +
			'<input type="button" value="JSON Visualize" id="ttPF_JSONCTA" style="display: none; margin-top: 10px;" /> ' +
			'<input type="text" placeholder="type here for filter, remove all for no filter" value="" id="ttPF_JSON_Filter" style="display: none; margin-top: 10px;margin-top: 10px;float: right;width: 50%;text-align: right;padding: 2px 10px;" /> ' +
			'<div style="clear:both;"></div>' +
			'</form>');
	}



	//jQuery Case Insensitive contains
	$.extend($.expr[':'], {
		'containsi': function(elem, i, match, array)
		{
			return (elem.textContent || elem.innerText || '').toLowerCase()
				.indexOf((match[3] || "").toLowerCase()) >= 0;
		}
	});

	if (typeof cookieRead('membershipID')!="undefined"){
		$('#ttPF_MembID').val(cookieRead('membershipID'));
	}

	var ttinshead = document.getElementsByTagName('head')[0];
	var ttinscss = document.createElement("style");
	ttinscss.type = "text/css";
	ttinscss.innerHTML = "body {font-size: 12px; font-family: Verdana;}" +
		".package {margin-left:10px;padding:3px;border-radius:2px;margin-top:2px;}" +
		"	.header {cursor:pointer;}" +
		".name {color:gray;}" +
		".array {background-color:#FFD8BB;border:thin solid #FFB780;}" +
		".object {background-color:#E7F1FE;border:thin solid #7DA2CE;}" +
		".string {color:red;}" +
		".number {color:blue;}" +
		".function {color:green;}" +
		".open .children {display:block;}" +
		".closed .children {display:none;}" +
		".arrow {background-image:url();" +
		" background-repeat:no-repeat; background-color:transparent; height:15px; width:15px; display:inline-block;}" +
		".open .arrow {background-position:-20px 0;}" +
		".closed .arrow {background-position:0 0;}" +
		".type {color:gray;font-size:8pt;float:right;}" +
		".hide {display:none;}";
	ttinshead.appendChild(ttinscss);

	$('#ttPF_form').submit(function(){
		if (location.host=="barclaysbankplc.tt.omtrdc.net"){

			$.ajax({
				url: 'https://barclaysbankplc.tt.omtrdc.net/rest/v1/profiles/thirdPartyId/'+$('#ttPF_MembID').val()+'?client=barclaysbankplc',
				cache: false,
				timeout: 18000,
				dataType: 'text',
				xhrFields: {
					withCredentials: true
				}, beforeSend: function () {
					$('#ttPF_RAW').html('');
					$('#ttPF_RAW, #ttPF_RAWText').hide();
					$('#ttFetchLoaderIco').show();
					$('#ttPF_JSON_Filter').val('');
				}, success: function (data) {
					$('#ttFetchLoaderIco').hide();
					$('#ttPF_RAW').html(data).show();
					$('#ttPF_RAWText').show();
					//Get the value from the input field
					var json_string = data;

					//Parse the json string
					try
					{
						//eval
						eval("var json=" + json_string);
						visualize(json);
					}
					catch (e)
					{
						alert("Sorry error in json string, please correct and try again: " + e.message);
					}
				}, error: function (data) {
					$('#ttFetchLoaderIco').hide();
					$('#ttPF_RAW').html(data.responseText).show();
					$('#ttPF_RAWText').show();
					//Get the value from the input field
					var json_string = data.responseText;

					//Parse the json string
					try
					{
						//eval
						eval("var json=" + json_string);
						visualize(json);
					}
					catch (e)
					{
						alert("Sorry error in json string, please correct and try again: " + e.message);
					}
				}
			});


		}else{
			$('#ttFetchLoaderIco').show();
			$('#ttPF_Iframe').attr('src','https://barclaysbankplc.tt.omtrdc.net/rest/v1/profiles/thirdPartyId/'+$('#ttPF_MembID').val()+'?client=barclaysbankplc').show();
			$('#ttPF_RAWText, #ttPF_ConvertTAText, #ttPF_JSONCTA, #ttPF_ConvertTA').show();
		}
		$('#ttPF_ConvertTA, #ttPF_RAWText, #ttPF_ConvertTAText, #ttPF_ConvertTAOutput').val('');
		$('#ttPF_ConvertTAOutput, #ttPF_JSON_Filter').hide();

		return false;
	});

	$("#ttPF_JSON_Filter").keyup(function(e) {

		// executed only 100 ms after the last keyup event.
		ttTypeWatch(function () {
			var inpVal = $("#ttPF_JSON_Filter").val();
			if (inpVal!=''){
				$('#ttPF_ConvertTAOutput>div>div>div.package.object>.children>.package').show();
				$('#ttPF_ConvertTAOutput>div>div>div.package.object>.children>.package:not(:containsi("'+inpVal+'"))').hide();
			}else{
				$('#ttPF_ConvertTAOutput>div>div>div.package.object>.children>.package').show();
			}
		}, 100);
	});



	$('#ttPF_JSONCTA').click(function(){

		//Get the value from the input field
		var json_string = $('#ttPF_ConvertTA').val();

		//Parse the json string
		try
		{
			//eval
			eval("var json=" + json_string);


			visualize(json);
		}
		catch (e)
		{
			alert("Sorry error in json string, please correct and try again: " + e.message);
		}


	});

	$('#ttPF_Iframe').load(function() {
		$('#ttFetchLoaderIco').hide();
	});


}

// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

	if (typeof $ == 'function') {
		// warning, global var
		thisPageUsingOtherJSLibrary = true;
	}

	function getScript(url, success) {

		var script     = document.createElement('script');
		script.src = url;

		var head = document.getElementsByTagName('head')[0],
			done = false;

		// Attach handlers for all browsers
		script.onload = script.onreadystatechange = function() {

			if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

				done = true;

				// callback function provided as param
				success();

				script.onload = script.onreadystatechange = null;
				head.removeChild(script);

			}

		};

		head.appendChild(script);

	}

	getScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function() {

		if (typeof jQuery=='undefined') {

			// Super failsafe - still somehow failed...

		} else {

			ttProfileFetch();

		}

	});

} else { // jQuery was already loaded

	// Run your jQuery Code
	ttProfileFetch();

}